<template>
	<view class="cu-list menu card-menu  margin-bottom-xl shadow-lg">
		<block v-for="(item,index) in btDevices" :key="index">
			<view class="cu-item arrow" hover-class="touch" @tap="blueToothItemTap(item)">
				<view class="content">
					<text class="text-grey">{{item.name}}</text>
				</view>
			</view>
		</block>
	</view>
</template>

<script>
import putyBleUtils from '../../static/js/putyBleUtils.js'
export default {
	data() {
		return {
			//设备信息
			btDevices: [],
			//是否搜索中
			pullRefresh: false,
			//定时器
			timeOut: null,
		}
	},
	onUnload() {
		putyBleUtils.stopBluetoothDevicesDiscovery();
		putyBleUtils.closeBluetoothAdapter();
		if (this.timeOut) {
			clearTimeout(this.timeOut)
		}
	},
	onLoad(options) {
		this.findPullDownRefresh()
	},
	methods: {
		blueToothItemTap(item){
			uni.setStorageSync('bleDevice', item)
            uni.navigateBack({
                delta: 1
            });
			// uni.reLaunch({url:"/pages/escPage/escPage"})
		},
		//刷新
		findPullDownRefresh() {
			if (this.pullRefresh) {
				return;
			}
			this.pullRefresh = true;
			this.btDevices = [];
			this.startBluetoothDevicesDiscovery();
		},
		//开始扫描蓝牙
		async startBluetoothDevicesDiscovery() {
			try {
				await putyBleUtils.openBluetoothAdapter();
				this.pullRefresh = true;
				let res = await putyBleUtils.startBluetoothDevicesDiscovery(10000, false);
                // console.log(res)
				this.onBluetoothDeviceFound();
				this.timeOut = setTimeout(() => {
					this.pullRefresh = false;
					clearTimeout(this.timeOut)
					this.timeOut = null;
				}, 13000)
			} catch (error) {
				if (error && error.errCode == 10008) {
					this.timeOut = setTimeout(() => {
						this.pullRefresh = false;
						this.findPullDownRefresh()
						clearTimeout(this.timeOut)
						this.timeOut = null;
					}, 3000)
				} else {
					this.pullRefresh = false;
					// console.log(error)
				}
			}
		},
		//接收到打印机设备
		async onBluetoothDeviceFound() {
			await putyBleUtils.onBluetoothDeviceFound(async res => {
                // console.log(res)
				let cache = await putyBleUtils.getBluetoothDevices()
				let btDevices = [];
				btDevices.push(...cache.devices);
				btDevices.push(...res);
				let obj = {}
				btDevices = btDevices.filter(c => c.name);
				this.btDevices = btDevices;
			});
		},
	}
}
</script>

<style>
.cu-item{
    padding: 35rpx;
    background: #cee;
}
</style>
